<template>
	<!-- 产品发布 -->
	<view class="">
		<view class="status_bar"><!-- 这里是状态栏 --></view>
		<u-navbar
			title="产品发布"
			@leftClick="toBack"
			:bgColor="'#CF1526'"
			leftIconColor="#ffffff"
			titleStyle="color:#ffffff"
			:safeAreaInsetTop="true"
			:placeholder="true"
		></u-navbar>
		<view class="h4 bg-white container form_warp">
			<u--form labelPosition="left" :model="productFrom" ref="productFrom" labelWidth="100" :rules="rules">
				<u-form-item label="产品名称" prop="product_name" borderBottom>
					<u--input v-model="productFrom.product_name" maxlength="50" border="none" placeholder="请编辑"></u--input>
				</u-form-item>
				<u-form-item label="产品分类" prop="mid " borderBottom>
					<view class="flex justify-end" @click="midShow = true">
						<view class="font" style="color: #c0c4cc;" v-if="!productFrom.mid">请选择</view>
						<view v-else class="font">{{ proCate(productFrom.mid) }}</view>
					</view>
					<!-- <u--input :value="proCate(productFrom.mid)" disabledColor="#fff" border="none" placeholder="请选择" @focus="hideKey(), (midShow = true)"></u--input> -->
				</u-form-item>
				<u-picker
					:show="midShow"
					:columns="productCate"
					keyName="title"
					title="请选择产品分类"
					@confirm="midConfirm"
					@cancel="midShow = false"
					@change="hideKey"
				></u-picker>
				<u-form-item label="产品品牌" prop="product_name" borderBottom>
					<!-- <u--input v-model="productFrom.product_name" maxlength="50" border="none" placeholder="请编辑"></u--input> -->
					<view class="flex justify-end" @click="getBrand">
						<view class="font" style="color: #c0c4cc;" v-if="!productFrom.product_brand">请选择</view>
						<view v-else class="font">{{ proBrand(productFrom.product_brand) }}</view>
					</view>
				</u-form-item>
				<u-form-item label="产品分类" prop="label" borderBottom>
					<u--input v-model="productFrom.label" maxlength="50" border="none" placeholder="多个分类请用逗号分隔"></u--input>
				</u-form-item>
				<u-form-item label="发布时间" prop="release_time" borderBottom>
					<view class="flex justify-end" @click="dataShow = true">
						<view class="font" style="color: #c0c4cc;" v-if="!productFrom.release_time">请选择</view>
						<view v-else class="font">{{ productFrom.release_time }}</view>
					</view>
				</u-form-item>
				<u-calendar :show="dataShow" mode="single" :safe-area-inset-bottom="true" @confirm="dataConfirm" @close="dataShow = false"></u-calendar>
				<u-picker
					:show="brandShow"
					:columns="productbrand"
					keyName="title"
					title="请选择产品品牌"
					@confirm="brandConfirm"
					@cancel="brandShow = false"
					@change="hideKey"
				></u-picker>
				<view class="img_warp">
					<u-form-item label="产品图片" prop="img_list" borderBottom>
						<view class="upload_img_box py-2">
							<u-upload
								:fileList="productFrom.img_list"
								capture="['album', 'camera']"
								uploadIcon="plus"
								uploadIconColor="#fff"
								width="105"
								height="70"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="10"
								:max-size="600 * 1024"
								@oversize="oversize"
							></u-upload>
						</view>
					</u-form-item>
				</view>
				<view class="img_warp">
					<u-form-item label="产品简介" prop="profile"><textarea class="textarea mt-2 p-1" v-model="productFrom.profile"></textarea></u-form-item>
				</view>
				<u-form-item label="产品详情" prop="content">
					<view class="flex justify-end" @click="editShow = true">
						<view class="font" style="color: #c0c4cc;">请编辑</view>
						<u-icon color="#666666" name="arrow-right"></u-icon>
					</view>
				</u-form-item>
				<view v-if="productFrom.content" class="cont_warp view"><u-parse :content="productFrom.content"></u-parse></view>
			</u--form>
		</view>
		<view class="bottom_btn"><button class="h4 text-white rounded-0" @click="submit">确认发布</button></view>
		<view class="edit_warp bg-white fixed-top" v-if="editShow"><parse-edit :html="productFrom.content" @getHtml="getHtml" @editBack="editBack"></parse-edit></view>
	</view>
</template>

<script>
import { productCategory, getProductBrands } from '@/api/home/nav/product_data.js';
import { productAddEdit, productEdit } from '@/api/my/publish.js';
import { uploadImage } from '@/api/common.js';
import parseEdit from './product_img_edit.vue';
import { baseUrl } from '@/util/api.js';
export default {
	components: {
		parseEdit
	},
	data() {
		return {
			productFrom: {
				id: '',
				mid: '', //产品分类id
				product_name: '',
				product_brand: '',
				label: '',
				release_time: '',
				profile: '',
				content: '',
				img_list: []
			},
			productCate: [], //产品分类
			midShow: false,
			rules: {
				product_name: [
					{
						type: 'string',
						required: true,
						message: '请输入产品名称',
						trigger: ['blur', 'change']
					}
				]
			},
			editShow: false,
			backStop: false,
			brandShow: false,
			productbrand: [],
			dataShow: false
		};
	},
	computed: {
		proCate(val) {
			return function(val) {
				if (this.productCate[0] && this.productCate[0].length >= 1) {
					let test = this.productCate[0].filter(item => item.id == val);
					return test[0]?.title;
				}
			};
		},
		proBrand(val) {
			return function(val) {
				if (this.productbrand[0] && this.productbrand[0].length >= 1) {
					let test = this.productbrand[0].filter(item => item == val);
					return test[0];
				}else{
					return val
				}
			};
		}
	},
	onLoad(option) {
		this.getCate();
		// 回显
		if (option.id) {
			this.productFrom.id = option.id; //产品id
			this.getInfo();
		}
	},
	methods: {
		// 获取编辑回显信息
		getInfo() {
			productEdit({
				id: this.productFrom.id
			})
				.then(res => {
					// console.log(res);
					if (res.code == 0) {
						this.productFrom = res.data;
					} else {
						uni.$u.toast(res.msg);
					}
				})
				.catch(err => {
					console.log('获取图文详情失败', err);
				});
		},
		// 获取产品分类
		getCate() {
			productCategory()
				.then(res => {
					if (res.code == 0) {
						this.productCate = [res.data];
					} else {
						uni.$u.toast(res.msg);
					}
				})
				.catch(err => {
					console.log('获取产品分类失败', err);
				});
		},
		// 选择分类
		midConfirm(e) {
			this.productFrom.mid = e.value[0].id;
			this.midShow = false;
			this.productFrom.product_brand = '';
		},
		// 获取产品品牌
		getBrand() {
			if (!this.productFrom.mid) {
				uni.$u.toast('请先选择产品分类');
			} else {
				this.brandShow = true;
				getProductBrands({
					mid: this.productFrom.mid
				}).then(res => {
					if (res.code == 0) {
						this.productbrand = [res.data];
					} else {
						uni.$u.toast(res.msg);
					}
				});
			}
		},
		// 选择品牌
		brandConfirm(e) {
			this.productFrom.product_brand = e.value[0];
			this.brandShow = false;
		},
		// 选择时间
		dataConfirm(e) {
			// console.log('选择日期', e);
			this.productFrom.release_time = e[0];
			this.dataShow = false;
		},
		submit() {
			let imgs = [];
			this.$refs.productFrom
				.validate()
				.then(res => {
					// console.log('确认发布');
					let msg = {
						uid: uni.getStorageSync('userInfo').userId || '',
						...this.productFrom,
						img_list: JSON.parse(JSON.stringify(this.productFrom.img_list)).map(item => item.url)
					};
					productAddEdit(msg)
						.then(res => {
							uni.$u.toast(res.msg);
							setTimeout(() => {
								uni.navigateTo({
									url: '../index'
								});
							}, 500);
						})
						.catch(err => {
							console.log('发布失败', err);
						});
				})
				.catch(errors => {
					uni.$u.toast('请正确填写产品信息');
				});
		},
		// 删除图片
		deletePic(event) {
			this.productFrom.img_list.splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this.productFrom.img_list.length;
			lists.map(item => {
				this.productFrom.img_list.push({
					// ...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i]);
				let item = this.productFrom.img_list[fileListLen];
				this.productFrom.img_list.splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '上传成功',
						url: result
					})
				);
				fileListLen++;
			}
		},
		uploadFilePromise(e) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: baseUrl + '/model/common/layer_upload_img',
					filePath: e.url,
					name: 'file',
					// formData: e,
					success: res => {
						if (res.statusCode == 200) {
							let msg = JSON.parse(res.data);
							console.log(msg);
							setTimeout(() => {
								resolve(msg.img);
							}, 1000);
						} else {
							uni.$u.toast('图片上传失败');
						}
					}
				});
			});
		},
		// 编辑返回
		editBack(val) {
			this.editShow = val;
		},
		// 编辑完成的内容
		getHtml(val) {
			this.productFrom.content = JSON.parse(decodeURIComponent(val));
			this.editShow = false;
		},

		// 返回监听
		toBack() {
			uni.navigateBack({
				delta: 1
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}

/*  #ifdef MP-WEIXIN */
.form_warp {
	margin-top: -25rpx;
}

/*  #endif  */
.cont_warp {
	padding-bottom: 100rpx;
}

.j {
	width: 100%;
	// margin-top: 100rpx;
}

.bottom_btn {
	width: 100%;
	position: fixed;
	bottom: 0;
	left: 0;

	button {
		height: 98rpx;
		background-color: $color14;
		line-height: 98rpx;
	}
}

.edit_warp {
	width: 100%;
	height: 100%;
	min-height: 100vw;
	z-index: 100;
}

.textarea {
	width: 100%;
	height: 220rpx;
	background: #ffffff;
	border: 1px solid #c0c0c0;
}

::v-deep .uni-input-input {
	text-align: right;
	color: #666666;
}

::v-deep .uni-input-placeholder {
	text-align: right;
}

::v-deep .u-form-item__body__right__message {
	text-align: right;
}

::v-deep .img_warp .u-form-item__body__right__content__slot {
	justify-content: flex-start;
	// padding-right: 20rpx;
}

::v-deep .u-form-item__body__right__content__slot {
	justify-content: flex-end;
	padding-right: 20rpx;
}

::v-deep .u-input__content__field-wrapper__field {
	text-align: right !important;
}

::v-deep .img_warp .u-form-item__body {
	display: block !important;
}
</style>
